package com.killer.gateway.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        if (request.getURI().getPath().contains("/admin/login")||request.getURI().getPath().contains("/auth/login")) {
            //如果是登录则放行
            return chain.filter(exchange);
        }
        //获取请求头
        HttpHeaders headers = request.getHeaders();
        //从请求头中获取令牌
        String token = headers.getFirst(AUTHORIZE_TOKEN);
        if (StringUtils.isEmpty(token)) {
            //没有令牌则返回无权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回
            return response.setComplete();
        }
        //判断令牌是否以bearer开头
        if (!token.startsWith("bearer") && !token.startsWith("Bearer")) {
//            请求头中每次需要添加一个Authorization头信息，头的结果为bearer token。
//            header:Authorization = bearer token
            token="bearer "+token;
        }
        //如果请求头中没有包含令牌信息，将令牌放入请求头后放行
        if (!request.getHeaders().containsKey("Authorization")) {
            request.mutate().header("Authorization", token);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
